import { useState, useRef, useEffect } from "react";

const useTheme = () => {
  const [theme, setTheme] = useState<"light" | "dark">("light");
  const [masking, setMasking] = useState(false);
  const [nextTheme, setNextTheme] = useState<"light" | "dark">("light");
  const maskRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const html = document.documentElement;
    if (theme === "dark") {
      html.classList.add("dark");
    } else {
      html.classList.remove("dark");
    }
    return () => html.classList.remove("dark");
  }, [theme]);

  const handleThemeSwitch = () => {
    setNextTheme(theme === "dark" ? "light" : "dark");
    setMasking(true);
  };

  useEffect(() => {
    if (!masking) return;
    const timer = setTimeout(() => {
      setTheme(nextTheme);
      setMasking(false);
    }, 700);
    return () => clearTimeout(timer);
  }, [masking, nextTheme]);

  return {
    theme,
    handleThemeSwitch,
    masking,
    maskRef,
    maskColor: theme === "dark" ? "#fff" : "#181c27",
  };
};

export default useTheme;
